using System;
using System.Threading;
using System.Threading.Tasks;

namespace Live.Refresh.Components
{

    public abstract class Watchable
    {
        public INotify Notify { get; set; }
        public ILogger Logger { get; set; }

        public IConfigurable Configurable { get; set; }

        public abstract string Name { get;}

        public bool IsStarted { get; set; }

        public CancellationTokenSource ThreadToken { get; set; }

        public virtual int Order
        {
            get { return 100; }//Default order to display on TAB
        }

        public void StartNotify()
        {
            try
            {
                Logger.Debug("started notification");
                ThreadToken = new CancellationTokenSource();
                Task.Factory.StartNew(Start, ThreadToken.Token);
                IsStarted = true;
            }
            catch (Exception ex)
            {
                Logger.Error("started notification", ex);
                Stop();
                IsStarted = false;
            }
        }

        protected abstract void Start();

        public abstract void OnStop();

        public void Stop()
        {
            Logger.Debug("Stoped");
            OnStop();
            ThreadToken.Cancel();
            IsStarted = false;
        }

        public override string ToString()
        {
            Logger.Debug("called to string");
            return this.Name;
        }
    }
}